package org.finesys.common.xss.filter;

import org.finesys.common.xss.properties.XssProperties;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class XssFilter extends OncePerRequestFilter {

    private final XssProperties xssProperties;
    private final PathMatcher pathMatcher;

    public XssFilter(XssProperties xssProperties, PathMatcher pathMatcher) {
        this.xssProperties = xssProperties;
        this.pathMatcher = pathMatcher;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        filterChain.doFilter(new XssRequestWrapper(request), response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        if (!xssProperties.isEnable()) {
            return true;
        }
        return xssProperties.getIgnoreUrls().stream().anyMatch(excludeUrl -> pathMatcher.match(excludeUrl, request.getRequestURI()));
    }
}
